/* eslint-disable no-unused-vars */
import Element from '../graphic/Element';
import Group from '../graphic/Group';
import Text from '../graphic/Text';

class BORect extends Group {
  constructor(options = {}) {
    super(options);
    console.log(options);
    /**
     * @property {String} type
     */
    this.type = 'BORect';

    this.title = options.title || 'BO_Title';

    /**
     * JSON like Array.
     * [{name:"userName",type="String"}]
     */
    this.fields = options.fields && options.fields.length ? [...options.fields] : [];

    this.createFieldComponents();
  }

  createFieldComponents() {
    this.add(
      new Text({
        style: {
          x: 0,
          y: 0,
          text: this.title,
          textFont: '24px Microsoft Yahei',
          textPadding: [10, 10],
          textPosition: 'insideLeft',
          textFill: '#393e46',
        },
        draggable: false,
      }),
    );

    this.fields.forEach((field, index) => {
      this.add(
        new Text({
          style: {
            x: 0,
            y: (18 + 10) * (index + 2), //这里的 18 是字号，注意：这里手动计算高度有风险
            text: `${field.name}   ${field.type}`,
            textFont: '18px Microsoft Yahei',
            textPadding: [10, 10],
            textPosition: 'insideLeft',
            textFill: '#393e46',
          },
          draggable: false,
        }),
      );
    });
  }

  render() {
    super.render();

    this.removeAll();

    this.createFieldComponents();
  }

  /**
   * 添加一个字段，name 不能重复
   * JSON like Array.
   * [{name:"userName",type="String"}]
   * @param {*} field
   * @returns
   */
  addField(field) {
    let exists = false;
    this.fields &&
      this.fields.length &&
      this.fields.forEach(item => {
        if (item.name === field.name) {
          console.error(`Field ${item.name} already exists, add failed.`);
          exists = true;
        }
      });

    if (exists) return;
    this.fields.push(field);
  }

  /**
   * 根据 name 删掉一个字段
   * @param {*} name
   * @returns
   */
  removeField(name) {
    let exist = false;
    this.fields &&
      this.fields.length &&
      this.fields.forEach((item, index) => {
        if (item.name === name) {
          exist = true;
          this.fields.splice(index, 1);
          return;
        }
      });

    if (!exist) {
      console.warn(`Field ${name} does not exist.`);
      return;
    }

    //TODO:remove child components.
  }

  toJSONObject() {
    let result = Element.prototype.toJSONObject.call(this);
    result.linkable = this.linkable;
    result.title = this.title;
    result.fields = this.fields;
    result.nodeData = JSON.parse(JSON.stringify(this.fields));
    return result;
  }
}
export default BORect;
